package com.hy.enterprise.framework.service.spring;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class MySpringUtil {
	private static Log logger = LogFactory.getLog(MySpringUtil.class);

	private static WebApplicationContext springContext = null;   

	public static WebApplicationContext getWebApplicationContext() {
		
		if(springContext==null) {
			
			throw new RuntimeException("springContext 为空！");
		} else {
			return springContext;
		}
		
	}
	
	public static Object getSpringComponent(String componentName) {
		springContext = getWebApplicationContext();
        return springContext.getBean(componentName);

	}
	
	public static Object getSpringComponent(Class componentClass) {
		springContext = getWebApplicationContext();
        return springContext.getBean(componentClass);

	}
	
	public static WebApplicationContext createWebApplicationContext(ServletContext servletContext) {
		if(springContext==null) {
			
			springContext = WebApplicationContextUtils.getWebApplicationContext(     
					servletContext);  //读取配置文件  
			
			logger.info("WebApplicationContextUtils,创建WebApplicationContext");
			return springContext;
		}else {
			logger.info("WebApplicationContextUtils,已经创建创建WebApplicationContext");
			return springContext;
			
		} 
	}

}
